<template>
  <div class="admin-verification-manager">
    <!-- 密码验证区域 -->
    <div v-if="!isAuthenticated" class="password-auth">
      <div class="auth-card">
        <h2 class="auth-title">管理员验证</h2>
        <div class="auth-form">
          <div class="input-group">
            <label>管理员密码</label>
            <input 
              v-model="adminPassword" 
              type="password" 
              placeholder="请输入管理员密码"
              @keyup.enter="authenticate"
              class="password-input"
            />
          </div>
          <button @click="authenticate" class="auth-btn">验证</button>
          <div v-if="authError" class="error-message">{{ authError }}</div>
        </div>
      </div>
    </div>

    <!-- 验证码管理区域 -->
    <div v-else class="verification-manager">
      <div class="header">
        <h2 class="title">
          <i class="fa-solid fa-shield-halved"></i>
          验证码管理
        </h2>
        <div class="controls">
          <button @click="loadPendingCodes" :disabled="loading" class="refresh-btn">
            <i class="fa-solid fa-refresh" :class="{ 'animate-spin': loading }"></i>
            刷新
          </button>
          <button @click="cleanExpiredCodes" :disabled="cleaning" class="clean-btn">
            <i class="fa-solid fa-trash" :class="{ 'animate-spin': cleaning }"></i>
            清理过期
          </button>
          <button @click="logout" class="logout-btn">
            <i class="fa-solid fa-sign-out-alt"></i>
            退出
          </button>
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="search-section">
        <div class="search-box">
          <i class="fa-solid fa-search"></i>
          <input 
            v-model="searchPhone" 
            type="tel" 
            placeholder="输入手机号搜索验证码"
            @input="searchCodes"
            class="search-input"
          />
        </div>
        <div class="search-tip">输入完整手机号查看该用户的所有验证码记录</div>
      </div>

      <!-- 验证码列表 -->
      <div v-if="loading" class="loading">
        <i class="fa-solid fa-spinner fa-spin"></i>
        <span>加载中...</span>
      </div>

      <div v-else-if="filteredCodes.length === 0" class="empty">
        <i class="fa-solid fa-inbox"></i>
        <span>{{ searchPhone ? '未找到相关验证码' : '暂无验证码记录' }}</span>
      </div>

      <div v-else class="codes-list">
        <div 
          v-for="code in filteredCodes" 
          :key="code.id"
          class="code-item"
          :class="{ 'expired': isExpired(code.expireTime), 'used': code.used }"
        >
          <div class="code-header">
            <div class="phone-info">
              <i class="fa-solid fa-phone"></i>
              <span class="phone">{{ code.phone }}</span>
            </div>
            <div class="status-badge" :class="getStatusClass(code)">
              {{ getStatusText(code) }}
            </div>
          </div>
          
          <div class="code-content">
            <div class="code-number">{{ code.code }}</div>
            <div class="time-info">
              <div class="time-item">
                <i class="fa-solid fa-clock"></i>
                <span>创建: {{ formatDateTime(code.createTime) }}</span>
              </div>
              <div class="time-item">
                <i class="fa-solid fa-hourglass-end"></i>
                <span>过期: {{ formatDateTime(code.expireTime) }}</span>
              </div>
              <div v-if="!isExpired(code.expireTime) && !code.used" class="time-remaining">
                <i class="fa-solid fa-timer"></i>
                <span>剩余: {{ getTimeRemaining(code.expireTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats">
        <div class="stat-item">
          <span class="stat-label">总记录:</span>
          <span class="stat-value">{{ allCodes.length }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">未使用:</span>
          <span class="stat-value">{{ unusedCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">已过期:</span>
          <span class="stat-value">{{ expiredCount }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import request from '../utils/request'

// 响应式数据
const isAuthenticated = ref(false)
const adminPassword = ref('')
const authError = ref('')
const loading = ref(false)
const cleaning = ref(false)
const allCodes = ref([])
const searchPhone = ref('')

// 计算属性
const filteredCodes = computed(() => {
  if (searchPhone.value) {
    return allCodes.value.filter(code => 
      code.phone.includes(searchPhone.value)
    )
  }
  return allCodes.value
})

const unusedCount = computed(() => 
  allCodes.value.filter(code => !code.used).length
)

const expiredCount = computed(() => 
  allCodes.value.filter(code => isExpired(code.expireTime)).length
)

// 生命周期
onMounted(() => {
  // 每次访问都需要重新输入密码，不保存认证状态
  isAuthenticated.value = false
  localStorage.removeItem('admin_auth')
})

// 认证方法
const authenticate = () => {
  if (adminPassword.value === '525612tx') {
    isAuthenticated.value = true
    loadPendingCodes()
    authError.value = ''
  } else {
    authError.value = '密码错误'
  }
}

// 退出登录
const logout = () => {
  isAuthenticated.value = false
  adminPassword.value = ''
  localStorage.removeItem('admin_auth')
  allCodes.value = []
}

// 加载验证码
const loadPendingCodes = async () => {
  loading.value = true
  try {
    const { data } = await request.get('/api/auth/pending-codes')
    if (data.code === 200) {
      allCodes.value = data.data || []
    } else {
      console.error('加载验证码失败:', data.message)
    }
  } catch (error) {
    console.error('加载验证码失败:', error)
  } finally {
    loading.value = false
  }
}

// 清理过期验证码
const cleanExpiredCodes = async () => {
  cleaning.value = true
  try {
    const { data } = await request.post('/api/auth/clean-expired-codes')
    if (data.code === 200) {
      alert('过期验证码清理完成')
      loadPendingCodes()
    } else {
      alert('清理失败: ' + data.message)
    }
  } catch (error) {
    console.error('清理过期验证码失败:', error)
    alert('清理失败')
  } finally {
    cleaning.value = false
  }
}

// 搜索验证码
const searchCodes = () => {
  // 实时搜索，通过计算属性自动过滤
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 检查是否过期
const isExpired = (expireTime) => {
  if (!expireTime) return true
  return new Date(expireTime) < new Date()
}

// 获取剩余时间
const getTimeRemaining = (expireTime) => {
  if (!expireTime) return '已过期'
  
  const now = new Date()
  const expire = new Date(expireTime)
  const diff = expire - now
  
  if (diff <= 0) return '已过期'
  
  const minutes = Math.floor(diff / 60000)
  const seconds = Math.floor((diff % 60000) / 1000)
  
  if (minutes > 0) {
    return `${minutes}分${seconds}秒`
  } else {
    return `${seconds}秒`
  }
}

// 获取状态文本
const getStatusText = (code) => {
  if (code.used) return '已使用'
  if (isExpired(code.expireTime)) return '已过期'
  return '有效'
}

// 获取状态样式类
const getStatusClass = (code) => {
  if (code.used) return 'used'
  if (isExpired(code.expireTime)) return 'expired'
  return 'valid'
}
</script>

<style scoped>
.admin-verification-manager {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

/* 密码验证区域 */
.password-auth {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

.auth-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 400px;
  width: 100%;
}

.auth-title {
  color: #333;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: 600;
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-group {
  text-align: left;
}

.input-group label {
  display: block;
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.password-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.password-input:focus {
  outline: none;
  border-color: #667eea;
}

.auth-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s;
}

.auth-btn:hover {
  transform: translateY(-2px);
}

.error-message {
  color: #e74c3c;
  font-size: 14px;
  margin-top: 10px;
}

/* 验证码管理区域 */
.verification-manager {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

.title {
  color: #333;
  font-size: 28px;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title i {
  color: #667eea;
}

.controls {
  display: flex;
  gap: 12px;
}

.controls button {
  padding: 10px 16px;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.refresh-btn {
  background: #3498db;
  color: white;
}

.refresh-btn:hover:not(:disabled) {
  background: #2980b9;
  transform: translateY(-2px);
}

.clean-btn {
  background: #e74c3c;
  color: white;
}

.clean-btn:hover:not(:disabled) {
  background: #c0392b;
  transform: translateY(-2px);
}

.logout-btn {
  background: #95a5a6;
  color: white;
}

.logout-btn:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
}

.controls button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 搜索区域 */
.search-section {
  margin-bottom: 30px;
}

.search-box {
  position: relative;
  max-width: 400px;
}

.search-box i {
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.search-input {
  width: 100%;
  padding: 12px 16px 12px 48px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
}

.search-tip {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}

/* 加载和空状态 */
.loading, .empty {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.loading i, .empty i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ddd;
}

.loading span, .empty span {
  font-size: 18px;
}

/* 验证码列表 */
.codes-list {
  display: grid;
  gap: 16px;
  margin-bottom: 30px;
}

.code-item {
  background: #f8f9fa;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s;
}

.code-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.code-item.expired {
  background: #fff5f5;
  border-color: #fed7d7;
}

.code-item.used {
  background: #f0f9ff;
  border-color: #bfdbfe;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.phone-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.phone-info i {
  color: #667eea;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
}

.status-badge.valid {
  background: #d4edda;
  color: #155724;
}

.status-badge.expired {
  background: #f8d7da;
  color: #721c24;
}

.status-badge.used {
  background: #d1ecf1;
  color: #0c5460;
}

.code-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.code-number {
  font-size: 32px;
  font-weight: 700;
  color: #667eea;
  font-family: 'Courier New', monospace;
  letter-spacing: 4px;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  text-align: right;
}

.time-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #666;
}

.time-item i {
  color: #999;
}

.time-remaining {
  color: #e67e22;
  font-weight: 600;
}

/* 统计信息 */
.stats {
  display: flex;
  justify-content: center;
  gap: 40px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #333;
}

/* 动画 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .controls {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .code-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .time-info {
    text-align: center;
  }
  
  .stats {
    flex-direction: column;
    gap: 20px;
  }
}
</style>
